<?php
/**
 * 对外开放的接口
 * @author [chang] <[changaiqing@hupu.com]>
 */
class openController extends base
{

    private $wechat;

	public function __construct()
    {
        parent::__construct('outward');
        $this->init_wechat();
    }


    private function checkSignature()
    {
        $nonce = common::request('nonce', 'G');
        $timestamp = common::request('timestamp', 'G');
        $signature = common::request('signature', 'G');
        $appSecret = $this->config['im']['appSecret']; // 开发者平台分配的 App Secret。
        $local_signature = sha1($appSecret.$nonce.$timestamp); // 生成本地签名。
        
        if(strcmp($signature, $local_signature)===0){
            return true;
        } else {
            return false;
        }
    }




    /**
     * 初始化微信配置
     * @return [type] [description]
     */
    private function init_wechat(){

        $options = array(
            'token'=>'wechat', //填写应用接口的Token
            //'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
            'appid'=>'wx6e9f935be224ef2e', //填写高级调用功能的app id
            'appsecret'=>'cd92ec5e944c784c5a00d002af91635a', //填写高级调用功能的密钥
            'agentid'=>'1', //应用的id
            'debug'=>false, //调试开关
            'logcallback'=>'logg', //调试输出方法，需要有一个string类型的参数
        );
        require FILE . 'lib/wechat.class.php';
        $this->wechat = new Wechat($options);
    }


    /**
     * 消息同步
     * @return [type] [description]
     */
    public function doMessageSync(){

        if(!$this->checkSignature()){
            $this->result['status'] = array('code' => -1, 'msg' => '签名错误');
        }else{
        	$fromUserId = common::request('fromUserId', 'P');
        	$toUserId = common::request('toUserId', 'P');
        	$objectName = common::request('objectName', 'P');
        	$content = common::request('content', 'P');
        	$timestamp = common::request('timestamp', 'P');
            $channelType = common::request('channelType', 'P');


        	$data = array(
        		"fromUserId" => $fromUserId,
        		"toUserId" => $toUserId,
        		"objectName" => $objectName,
        		"content" => $content,
        		"timestamp" => $timestamp,
                "channelType" => $channelType
        	);
        	$this->load('message')->addMessageSync($data);
        }   
    }

    public function doWechatLogin()
    {
        // 活动结束提示
        if($this->time >= strtotime("2015-07-04"))
        {
            echo "<img style=\"width:100%;\" src=\"http://hupu-run.hupucdn.com/PostImg_b9a3999e8c97fbed617d242538a2d7bb.jpg\" >";
            exit;
        }
        
        $actId = common::request('actId', 'G');
        $type = common::request('type', 'G', 0);

        $code = common::request('code', 'G', '', TRUE);

        $redirect_uri = $this->load('activity')->getActivityUrl($actId);

        if($code){

            $access_token_info = $this->getAccessToken($code);

            $access_token = $access_token_info['access_token'];
            $openid = $access_token_info['openid'];

            $userInfo = $this->getUserInfo($access_token, $openid);

            $userInfo['access_token'] = $access_token;

            $this->load('weixin')->setAuthorUserInfo($userInfo);
        }

        $openid = $this->load('weixin')->encryptOpenId($openid);
        $redirect_uri = stripos($redirect_uri, '?') === false ? $redirect_uri.'?runid='.$openid : $redirect_uri.'&runid='.$openid;
        $redirect_uri .= '&type='.$type;
        common::go($redirect_uri);
    }


    private function getAccessToken($code = ''){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6e9f935be224ef2e&secret=cd92ec5e944c784c5a00d002af91635a&code=" . $code . "&grant_type=authorization_code";
        $rst= common::getContents($url);
        return json_decode($rst,true);
    }

    private function getUserInfo($access_token = '' , $openid = ''){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token. "&openid=" . $openid . "&lang=zh_CN";
        $rst = common::getContents($url);
        return json_decode($rst,true);
    }



    public function curl($action,$params){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $action);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $ret = curl_exec($ch);
            if (false === $ret) {
                    $ret =  curl_errno($ch);
            }
            curl_close($ch);
            return $ret;
    }

    
    /**
     * 微信网页授权登陆
     */
    public function dowxWebLogin()
    {
        $code = common::request('code', 'G', '', TRUE);
        $actId = common::request('actId', 'G');
        $type = common::request('type', 'G', 0);

        $redirect_uri = $this->load('activity')->getActivityUrl($actId);

        $logInfo = '['.date("Y-m-d H:i:s").']'."\tactId:[".$actId."]\t";
        $openid = '';  // 微信用户标识
        if($code)
        {
            // 获取授权信息
            $authorInfo = $this->load('weixin')->getuthorInfo($code);
            $logInfo .= '授权信息:';
            $logInfo .= is_array($authorInfo) ? urldecode(http_build_query($authorInfo, NULL, '&')) : $authorInfo;
            $logInfo .= "\n";

            if(!empty($authorInfo) && isset($authorInfo['access_token']) && isset($authorInfo['openid']))
            {
                $userInfo = $_ENV['weixin']->getUserInfo($authorInfo['access_token'], $authorInfo['openid']);
                $logInfo .= '用户信息:';
                $logInfo .= is_array($userInfo) ? urldecode(http_build_query($userInfo, NULL, '&')) : $userInfo;
                $logInfo .= "\n";
                if(isset($userInfo['openid']))
                {
                    $openid = $userInfo['openid'];

                    $userInfo['access_token'] = $authorInfo['access_token'];
                    $_ENV['weixin']->setAuthorUserInfo($userInfo);
                }
            }
        }
        $this->load('log')->writeLog('weixin', $logInfo, 'author.txt');

        $openid = $this->load('weixin')->encryptOpenId($openid);

        $redirect_uri = stripos($redirect_uri, '?') === false ? $redirect_uri.'?runid='.$openid : $redirect_uri.'&runid='.$openid;
        $redirect_uri .= '&type='.$type;

        common::go($redirect_uri);
    }
    /*
     * 更新 component_verify_ticket
     */
    public function donotify()
    {
        // 获取XML内容，并将其转为array
        $postStr = file_get_contents("php://input");

        $xmlArr = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        $logInfo = '['.date("Y-m-d H:i:s").']'.$postStr."\n";
        if (isset($xmlArr['Encrypt']))
        {
            $ComponentVerifyTicket = $this->load('weixin')->updateVerifyTiket($xmlArr['Encrypt']);
            $logInfo .= $ComponentVerifyTicket ."\n"; 
        }
        $this->load('log')->writeLog('weixin', $logInfo, 'notify.txt');
        exit('SUCCESS');
    }



    public function doCallback(){

        $this->load("weixin")->messageDecrypt("OGuVOvnjCIILWhUPDb18XsQvbcW6ccAPM2wLp9HiBDTVuf68G3wB9XIvomr52QRNqNhj9Lym1nmk5WTzw7tnPdeFMsUny5xUGZOoVZUN8/WcPjaEbaTPle4FjbDePJbrLuKwzSMfEtr6O9gWXTzqoEjhv3cB939LvHUJwoBEAwkXDvPAU1IcOa7Rgkkksb+8I7JbkBXY+jzkKQADFOH+IKntz3P3kEiUlG5I8emHP5Frk+iHIF3acHi85c6nl+gFawEgmdF4sWlqjs/nLyiwudGboX6hFuT5J/8zyVnATPJ71ySITZp1PPMfMUo+hg6ZG8npt8QAaNa0+dM4JUD2rZcqcriCzELBZFgdYSv5q4kIUZWbcm3N5wf28xvQkRh8B7u0fVEumvnE9pQOspsZ3RSQFZqEyjND15/UB9FT5Us=");

        $from = $this->wechat->getRev()->getRevFrom();
        $type = $this->wechat->getRev()->getRevType();
        $event = $this->wechat->getRev()->getRevEvent();
        $content = $this->wechat->getRev()->getRevContent();



        switch($type) {
            case Wechat::MSGTYPE_TEXT:
                    if("TESTCOMPONENT_MSG_TYPE_TEXT" == $content){
                        $this->wechat->text($content . "_callback")->reply();
                    }
                    if(strstr($content,'QUERY_AUTH_CODE')){
                        $query_auth_code_array = explode('QUERY_AUTH_CODE:', $content);
                        $this->wechat->text("")->replyEmpty();
                        $this->wechat->text_custom($from,$query_auth_code_array[1] . '_from_api')->send();
                    }
                    exit;
                    break;
            case Wechat::MSGTYPE_EVENT:
                    $this->wechat->text($event . "from_callback")->reply();
                    exit;
                    break;
            default:
                    $this->wechat->text("Sorry")->reply();
        }

        echo "callback";
    }

}
